function lines=img2lines(image)

% This function is calculating all lines in image

% Function Inputs:
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
% image - grayscale image matrix
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

% Function Outputs:
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
% lines - getting struct of -
%                                  i,j - coordinates of the line's points.
%                                   a_b - the linear coefs, like in y=ax+b
%-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

% parameters
TH_FACTOR=1.7;
EGDE_BINS=8;
PIX_N=10;   % deciding the line's minimum length

% calculating gradients
img=double(image);
flt=[1 0 -1];
dx=imfilter(img,flt);
dy=imfilter(img,flt');
grad=sqrt(abs(dx.^2)+abs(dy.^2));
orient=atan2(dy,dx);

% making histogram by orients
th=median(grad(:))*TH_FACTOR;
mask=(grad>th);
[na,centers]=hist(orient(mask),EGDE_BINS);
centers=[-Inf centers Inf];
nclasses=length(centers)-1;

% extracting x,y coordinates for all lines
count=0;
for i=1:nclasses;
    tmp=mask & (orient>centers(i)) & (orient<centers(i+1));
    [labs,nlab]=bwlabel(tmp,8);
    howm=hist(labs(labs>0),1:nlab);
    ok=find(howm>=PIX_N);
    tmp2=ismember(labs,ok);
    [labs,nlab]=bwlabel(tmp2,8);
    ind=find(labs~=0);
    line_number=labs(ind);
    [line_i,line_j]=ind2sub(size(labs),ind);
    for j=1:nlab
        count=count+1;
        indices=find(line_number==j);
        lines(count).i_support=line_i(indices);
        lines(count).j_support=line_j(indices);
        
        %calculating linear coef
        [C,dist]=fitline([lines(count).j_support'; lines(count).i_support']);
        if abs(C(2))<1e-5
            lines(count).a_b=[Inf;C(3)];
        else
            lines(count).a_b=-C([1 3])/C(2);
        end
        if median(dist)>1.5
            count=count-1;  % not a good line
        end

    end
end
